package com.winit.cloudlink.mgmt.recovery;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@Slf4j
public class MessageRestoreTaskManagerImpl implements MessageRestoreTaskManager {
    @Autowired
    private MessageSender messageSender;

    private Map<String, MessageRestoreTask> restoreTasks = Maps.newConcurrentMap();

    @Override
    public long restoreMessages(String messageFile) {
        if (restoreTasks.containsKey(messageFile)) {
            String msg = String.format("正在从文件'%s'恢复消息，无需再次执行.", messageFile);
            log.warn(msg);
            throw new MessageRestoreException(msg);
        }
        try {
            MessageRestoreTask messageRestoreTask = new MessageRestoreTask(messageFile, messageSender);
            restoreTasks.put(messageFile, messageRestoreTask);
            return messageRestoreTask.execute();
        } catch (Exception e) {
            String msg = String.format("从文件'%s'里恢复消息出错.", messageFile);
            log.warn(msg);
            throw new MessageRestoreException(msg);
        } finally {
            restoreTasks.remove(messageFile);
        }
    }
}
